package util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * this utility is used to read definition of supported database
 * 
 * @author Patrick
 * @date 2010.3.1
 */
public class PatrickXmlReader {
    /**
     * this method is used to get all the names which xls2DB supports and return String[] for ComboBox using
     * 
     * @return
     */
    public static String[] getTypeNames() {
        ArrayList<String> list = new ArrayList<String>();
        try {
            File defFile = new File("xml/supportDef.xml");// this path is begin from the project folder xls2DB
            SAXReader reader = new SAXReader();
            Document doc = reader.read(defFile);
            Element root = doc.getRootElement();
            Element foo;
            for (Iterator i = root.elementIterator("database"); i.hasNext();) {
                foo = (Element) i.next();
                list.add(foo.elementText("name"));
                System.out.print("databaseName:" + foo.elementText("name"));
            }
        } catch (Exception e) {
            System.out.print("xml reading failed....");
            e.printStackTrace();
        }
        return ArrayTransfer.transString(list);
    }
    /**
     * get database details of the given database name
     * @param databaseName
     * @return
     */
    public static Map<String,String> getDetail(String databaseName){
        Map<String,String> map=new HashMap<String,String>();
        try {
            File defFile = new File("xml/supportDef.xml");// this path is begin from the project folder xls2DB
            SAXReader reader = new SAXReader();
            Document doc = reader.read(defFile);
            Element root = doc.getRootElement();
            Element foo;
            for (Iterator i = root.elementIterator("database"); i.hasNext();) {
                foo = (Element) i.next();
                if(foo.elementText("name").equals(databaseName)){
                    map.put("name", databaseName);
                    map.put("driver", foo.elementText("driver"));
                    map.put("driverClass", foo.elementText("driverClass"));
                    map.put("xlsTransfer", foo.elementText("xlsTransfer"));
                    map.put("connectURL", foo.elementText("connectURL"));
                }
            }
        } catch (Exception e) {
            System.out.print("xml reading failed....");
            e.printStackTrace();
        }
        return map;
    }

}
